package com.mapper;

import android.text.TextUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by danger on 14/11/17.
 */
public class JsonMapper {

    public void parseJson(Object obj, String json) throws JSONException, IllegalAccessException {
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field filed : fields) {
            if (isTransient(filed)) {
                continue;
            }

            Class<?> clazz = filed.getType();

            JSONObject jsonObject = new JSONObject(json);
            String name = getName(filed);


            if (clazz.equals(Byte.class) || clazz.equals(byte.class)) {
                filed.set(obj, (byte) jsonObject.getInt(name));
            } else if (clazz.equals(Short.class) || clazz.equals(short.class)) {
                filed.set(obj, (short) jsonObject.getInt(name));
            } else if (clazz.equals(Integer.class) || clazz.equals(int.class)) {
                filed.set(obj, jsonObject.getInt(name));
            } else if (clazz.equals(Long.class) || clazz.equals(long.class)) {
                filed.set(obj, jsonObject.getLong(name));
            } else if (clazz.equals(Float.class) || clazz.equals(float.class)) {
                filed.set(obj, (float) (jsonObject.getDouble(name)));
            } else if (clazz.equals(Double.class) || clazz.equals(double.class)) {
                filed.set(obj, jsonObject.getDouble(name));
            } else if (clazz.equals(Character.class)) {
//                filed.set(obj, jsonObject.get(name));
            } else if (clazz.equals(Boolean.class) || clazz.equals(boolean.class)) {
                filed.set(obj, jsonObject.getBoolean(name));
            } else if (clazz.equals(String.class)) {
                filed.set(obj, jsonObject.getString(name));
            } else if (clazz.equals(List.class) || clazz.equals(ArrayList.class)) {
//                ArrayList<> list = new filed.set(obj, jsonObject.getString(name));
            }
        }
    }


    public static boolean isTransient(Field field) {
        return field.getAnnotation(Transparent.class) != null;
    }


    private String getName(Field field) {
        Name name = field.getAnnotation(Name.class);
        if (name != null && !TextUtils.isEmpty(name.name())) {
            return name.name();
        }

        return field.getName();
    }

}
